<template>
  <div v-loading="loading" class="app-container warehouse_order_add">
    <div class="header_title_box">
      <h2>基本信息</h2>
    </div>
    <el-form :ref="formName" inline :model="formFieldsData" :rules="rules">
      <div class="select_form_box">
        <!-- 出库单 -->
        <div class="filter-container">
          <el-form-item label="出库实体仓" prop="entity_warehouse_id">
            <el-select v-model="formFieldsData.entity_warehouse_id" filterable clearable placeholder="-请选择-" class="input-with-select mr64" @change="changeEntityWarehouseHandler">
              <el-option v-for="item in entityWarehouseList" :key="item.id" :value="item.id" :label="item.name" />
            </el-select>
          </el-form-item>
          <el-form-item label="出库虚拟仓" prop="virtual_warehouse_id">
            <el-select v-model="formFieldsData.virtual_warehouse_id" filterable clearable placeholder="-请选择-" class="input-with-select mr64" @change="changeVirtualWarehouseHandler">
              <el-option v-for="item in virtualWarehouseList" :key="item.id" :value="item.id" :label="item.name" />
            </el-select>
          </el-form-item>
          <el-form-item label="出库原因" prop="notes">
            <el-input v-model="formFieldsData.notes" class="input-with-select mr64" />
          </el-form-item>
        </div>
      </div>
      <div class="header_title_box">
        <h2>商品明细信息</h2>
      </div>
      <div class="operation_button_box">
        <el-button size="middle" type="primary" icon="el-icon-circle-plus-outline" @click="showAddProductsDialog">添加商品</el-button>
        <el-button size="middle" type="primary" @click="delProducts">批量删除</el-button>
      </div>
      <div v-loading="loading" class="warehouse_order_add_products">
        <el-table :data="formFieldsData.products" border fit @selection-change="tableSelectHandler">
          <el-table-column type="selection" width="51" align="center" />
          <el-table-column label="操作" align="center" width="109">
            <template slot-scope="scope">
              <span class="delete_style" style="margin: 0;" @click="delProduct(scope.row.goods_id)">删除</span>
            </template>
          </el-table-column>
          <el-table-column label="缩略图" prop="goods_pic" align="center" width="148">
            <template slot-scope="scope">
              <thund :img="scope.row.goods_pic | shopThund" />
            </template>
          </el-table-column>
          <el-table-column label="系统sku" prop="goods_code" align="center" width="182" />
          <el-table-column label="即时库存" prop="stock" align="center" width="205" />
          <el-table-column label="出库数量" prop="created_by_name" align="center" width="205">
            <template slot-scope="scope">
              <el-form-item :prop="`products.${ scope.$index }.number`" :rules="productNumberRule" class="mt22">
                <el-input-number v-model="scope.row.number" :precision="0" :min="1" :max="scope.row.stock" placeholder="手工输入" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="中文名称" prop="goods_name" align="center" width="208" />
          <el-table-column label="英文名称" prop="goods_name_en" align="center" width="258" />
          <el-table-column label="包装类型" align="center" width="167">
            <template slot-scope="scope">
              <dic-values :dictionaries="DICTIONARIES.splitOrder" :code="scope.row.packing_method" />
            </template>
          </el-table-column>
          <el-table-column label="商品分类" prop="category_name" align="center" width="203" />
        </el-table>
      </div>
    </el-form>

    <div class="warehouse_order_add_footer">
      <span class="warehouse_order_add_footer_btn">
        <el-button type="primary" :loading="btnLoading" @click="handleSubmit">保存</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </span>
    </div>
    <products-add-dialog ref="productsAdd" :url="productUrl" />
  </div>
</template>

<script>
import { action } from '@/directive/permission/index.js' // 权限判断指令
import productsAdd from '../../mixins/productAdd'
import chooseWarehouse from '../../mixins/chooseWarehouse'
export default {
  name: 'OutboundOrderAdd',
  directives: {
    action
  },
  mixins: [productsAdd, chooseWarehouse],
  data() {
    return {
      id: '', // 出库单id
      info: {}, // 出库单info
      formName: 'OrderForm', // form 名称
      productUrl: '/warehouse/product/list',
      formFieldsData: {
        entity_warehouse_id: '', // 实体仓
        virtual_warehouse_id: '', // 虚拟仓
        notes: '', // 出库原因
        products: [] // 商品列表
      },
      rules: {
        entity_warehouse_id: [
          { required: true, message: '请选择实体仓', trigger: 'blur' }
        ], // 实体仓
        virtual_warehouse_id: [
          { required: true, message: '请选择虚拟仓', trigger: 'blur' }
        ], // 虚拟仓
        notes: [
          { max: 500, message: '出库原因须在500个字符以内', trigger: 'blur' }
        ] // 出库原因
      },
      productNumberRule: [
        { required: true, message: '请输入数量', trigger: ['change', 'blur'] }
      ],
      btnLoading: false
    }
  },
  watch: {
    $route(router) {
      this.checkRouterHasId(router)
    }
  },
  created() {
    const vm = this
    vm.checkRouterHasId(vm.$route)
    const dataObj = window.localStorage.getItem('outboundOrder')
    if (dataObj) {
      vm.formFieldsData = JSON.parse(dataObj)
      if (vm.formFieldsData.entity_warehouse_id) {
        vm.getVirtualWarehouseList()
      }
    }
  },
  beforeDestroy() {
    if (!this.$route.params.id) {
      window.localStorage.setItem('outboundOrder', JSON.stringify(this.formFieldsData))
    }
  },
  methods: {
    // 修改实体仓handler
    changeEntityWarehouseHandler() {
      const vm = this
      vm.formFieldsData.virtual_warehouse_id = ''
      vm.formFieldsData.products = []
      vm.getVirtualWarehouseList()
    },
    // 修改虚拟仓库handler
    changeVirtualWarehouseHandler() {
      const vm = this
      vm.formFieldsData.products = [] // 商品是根据虚拟仓选择，所以也清空
    },
    // 修改调出仓handler
    changeTransferOutWarehouseHandler() {
      const vm = this
      vm.formFieldsData.products = []
    },
    // 检查路由是否有id
    checkRouterHasId(router) {
      const vm = this
      const id = router.params.id
      if (id) {
        vm.id = id
        vm.getInfo()
      }
    },
    // 获取详情
    getInfo() {
      const vm = this
      vm.loading = true
      vm.$http.get(`/outbound-order/${vm.id}`).then((res) => {
        vm.info = res.data
        vm.formFieldsData.entity_warehouse_id = res.data.entity_warehouse_id // 实体仓
        vm.formFieldsData.virtual_warehouse_id = res.data.virtual_warehouse_id // 虚拟仓
        vm.formFieldsData.notes = res.data.notes // 出库原因
        vm.formFieldsData.products = res.data.products // 商品列表
        vm.getVirtualWarehouseList(() => {
          vm.loading = false
          vm.getStockInWarehouse(vm.formFieldsData.products)
        })
      })
    },
    // 获取商品在虚拟仓库的即时库存
    getStockInWarehouse(arr) {
      const vm = this
      vm.productLoading = true
      const promiseAll = arr.map((e) => {
        return new Promise((resolve, reject) => {
          const virtualWarehouse = vm.virtualWarehouseList.find(e => e.id === vm.formFieldsData.virtual_warehouse_id)
          const params = {
            goods_code: e.goods_code,
            warehouse: virtualWarehouse.name
          }
          vm.$http
            .get('/stock', { params })
            .then((res) => {
              const data = res.data[0] || { available_stock: 0 }
              e['stock'] = data.available_stock
              resolve(e)
            })
            .catch((err) => {
              reject(err)
            })
        })
      })
      Promise.all(promiseAll)
        .then((res) => {
          vm.formFieldsData.products = res
          vm.productLoading = false
        })
        .catch((err) => {
          console.log('err-------------------')
          console.log(err)
          vm.productLoading = false
        })
    },
    // 显示添加商品弹窗
    showAddProductsDialog() {
      const vm = this
      if (!vm.formFieldsData.virtual_warehouse_id) {
        vm.$message.error('请先选择出库虚拟仓!')
        return
      }
      vm.$refs['productsAdd'].show({
        params: {
          id: vm.formFieldsData.virtual_warehouse_id,
          type: 2,
          is_disable: 1
        },
        success({ data }) {
          vm.setProducts(data)
        }
      })
    },
    // 设置产品列表
    setProducts(data) {
      const vm = this
      data.forEach(e => {
        const index = vm.formFieldsData.products.findIndex(ele => (ele.goods_id === e.id))
        if (index > -1) {
          vm.formFieldsData.products.splice(index, 1)
        }
        const item = {
          goods_id: e.id,
          goods_code: e.code,
          goods_name: e.name_ch,
          goods_name_en: e.name_en,
          category_name: e.category_name,
          goods_pic: e.image_url,
          packing_method: e.packing_method,
          stock: +e.available_stock,
          number: '',
          type: 1
        }
        vm.formFieldsData.products.push(item)
      })
    },
    // 取消
    handleCancel() {
      const vm = this
      vm.$refs[vm.formName].resetFields()
      vm.formFieldsData.products = []
      vm.$router.push({ path: '/storage/outboundOrder' })
    },
    // 保存
    handleSubmit() {
      const vm = this
      vm.$refs[vm.formName].validate((valid) => {
        if (valid) {
          if (vm.formFieldsData.products.length > 0) {
            vm.id ? vm.editOutboundOrder() : vm.addOutboundOrder()
          } else {
            vm.$message.error('请选择添加至少一个商品')
          }
        }
      })
    },
    // 添加出库单
    addOutboundOrder() {
      const vm = this
      vm.btnLoading = true
      vm.$http.post('/outbound-order', vm.formFieldsData).then((res) => {
        vm.$message.success('添加成功')
        vm.handleCancel()
        vm.btnLoading = false
      }).catch(() => {
        vm.btnLoading = false
      })
    },
    // 编辑出库单
    editOutboundOrder() {
      const vm = this
      vm.btnLoading = true
      vm.$http
        .put(`/outbound-order/${vm.id}`, vm.formFieldsData)
        .then((res) => {
          vm.$message.success('编辑成功')
          vm.handleCancel()
          vm.btnLoading = false
        }).catch(() => {
          vm.btnLoading = false
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.warehouse_order_add {
  .filter-container {
    padding-bottom: 0;
    border: none;
  }
  .puduct_input {
    width: 121px;
  }
  &_footer {
    width: 100%;
    text-align: center;
    margin: 46px 0;
  }
}
.warehouse_order_add .filter-container ::v-deep .el-form-item {
  display: inline-block;
}
.warehouse_order_add_footer ::v-deep .el-button + .el-button {
  margin-left: 64px;
}
.warehouse_order_add_products ::v-deep .el-form-item {
}
</style>
